package com.amigo.online.message.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 主库
 */
@Configuration
@MapperScan(basePackages = "com.amigo.online.message.mapper.message", sqlSessionTemplateRef  = "messageSqlSessionTemplate")
public class  MessageDataSource {

    @Bean(name = "messageData")
    @ConfigurationProperties(prefix = "spring.datasource.message") // application.properteis中对应属性的前缀
    @Primary
    public DataSource messageData() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "messageSqlSessionFactory")
    @Primary
    public SqlSessionFactory messageSqlSessionFactory(@Qualifier("messageData") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/mapper/message/*.xml"));
        return bean.getObject();
    }

    /**
     * 事务控制
     * @param dataSource
     * @return
     */
    @Bean(name = "messageTransactionManager")
    @Primary
    public DataSourceTransactionManager messageTransactionManager(@Qualifier("messageData") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "messageSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate messageSqlSessionTemplate(@Qualifier("messageSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}